﻿using System;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Guids;
using Volo.Abp.Timing;

namespace NewRetail.Application.Core.Entity
{
    public interface IEntityHelper
    {
        T InitEntity<T>(T model, DateTime? time = null) where T : BaseEntity;
        T SetCreationInfo<T>(T model, DateTime? time = null, int? creatorId = null) where T : BaseEntity;
        T SetUpdationInfo<T>(T model, DateTime? utc_time = null, int? updatorId = null) where T : BaseEntity;
    }

    public class DefaultEntityHelper : IEntityHelper, ITransientDependency
    {
        private readonly IGuidGenerator guidGenerator;
        private readonly IClock clock;
        public DefaultEntityHelper(IGuidGenerator guidGenerator, IClock clock)
        {
            this.guidGenerator = guidGenerator;
            this.clock = clock;
        }

        public T InitEntity<T>(T model, DateTime? time = null) where T : BaseEntity
        {
            var guid = this.guidGenerator.NewGuidString();
            model.SetId(guid);
            model = this.SetCreationInfo(model, time);
            this.TrySetNoWhenEmpty(model);
            this.SetUpdationInfo(model);
            return model;
        }

        void TrySetNoWhenEmpty<T>(T model) where T : BaseEntity
        {
            if (model is BaseEntityWithNo e && string.IsNullOrWhiteSpace(e.No))
            {
                e.No = e.Id;
            }
        }

        public T SetCreationInfo<T>(T model, DateTime? time = null, int? creatorId = null) where T : BaseEntity
        {
            model.addUserID = creatorId;
            model.addTime = time ?? this.clock.Now;
            return model;
        }

        /// <summary>
        /// 更新时间等信息
        /// </summary>
        public T SetUpdationInfo<T>(T model, DateTime? utc_time = null, int? updatorId = null) where T : BaseEntity
        {
            model.updateUserID = updatorId;
            model.updateTime = utc_time ?? this.clock.Now;
            return model;
        }
    }
}
